<?php
// Connects to hatestream db
function sqlConnect() {
	
	// SPECIFY THESE
	$USERNAME = "root";
	$PASSWORD = "test";
    // *************
	
	global $con;//prevents multiple simultaneous connections in one session, but why would you want that anyway?
    //130
    $con = mysql_connect("localhost:3306",$USERNAME,$PASSWORD);//not very safe
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("hatestream", $con);
}

function sqlClose() {
    global $con;
    echo mysql_error();//should go to log file or prettify for user
    mysql_close($con);
}

function multirow2Array ($resource) {
    $arr = Array();
    while($temp = mysql_fetch_assoc($resource)) {
        $arr[] = $temp;
    }
    return $arr;
}
//take an array with the variables that should be inserted and the query as a string with 
//format for where variables should be placed, this is for sanitizing purposes. NOT VALIDATING
function sqlQuery($query, $array=array() ,$getPrimaryKey = FALSE) {
    //this is probably inefficient if a lot of connections are opened over and over
    //thus options should be looked for.
    //1. Using persisten sql connections
    //2. When knowing lots of connections are to be used in a row, call sqlConnect()
    //   (a modified version of sqlQuery() if it tries to open connections even though it's already active
    //    probably have to since sqlClose() will fuck it up otherwise) and then sqlClose() when the querys are done
    if (!is_array($array)) {
        $array = array($array);
    }
    sqlConnect();
    foreach ($array as &$obj) {
        $obj = mysql_real_escape_string($obj);
    }
    $sqlquery = vsprintf($query,$array);
    //catch exceptions and shit O.o
    $result = mysql_query($sqlquery);
    if ($getPrimaryKey) {
    	$result = mysql_insert_id();
    }
    sqlClose();
    return $result;
}
?>